-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add calculator #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: dev
Are you sure you want to change the base?
Conversation
| String rounded = String.format("%.2f", price).replace(',', '.'); | ||
|
|
||
| // передаем уже округленное значение для гарантии консистентности | ||
| return String.format("%s %s", rounded, getPriceSpelling(Float.parseFloat(rounded))); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
благодаря этому финту, если мы в эту функцию передадим 1.9999, то на выходе будет строка "2.00 рубля", а не "2.00 рубль"
src/main/java/Main.java
Outdated
| final static private int MIN_PEOPLE_COUNT = 2; | ||
| final static private String FINISH_COMMAND = "Завершить"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Модификаторы класса и полей, если они присутствуют, отображаются в порядке, рекомендованном спецификацией языка Java:
public protected private abstract default static final transient volatile synchronized native strictfp
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
То есть здесь привычнее было бы видеть
private static final
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
спасибо, не знал =)
| String.format( | ||
| "На скольких человек разделить счет ? (значение должно быть >=%d)", | ||
| MIN_PEOPLE_COUNT | ||
| ) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Круто, что ты везде по максимуму используешь форматирование строк через String.format, т.к. это работает быстрее и требует меньше памяти, чем та же конкатенация строк. Есть ещё класс StringBuilder, который работает ещё быстрее чем String.format, можешь почитать о нём, а может и применишь и в этой практической работе
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
спасибо, почитаю
src/main/java/Main.java
Outdated
|
|
||
| calculator.add(product); | ||
|
|
||
| String command = TerminalReader.readString("Хотите добавить еще товар ?"); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Сейчас немного неочевидно для обычного пользователя, что нужно ввести "завершить", чтобы не вводить товар, я бы в это сообщение дописал об этом
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
справедливо
|
|
||
| public class TerminalReader { | ||
| final static private Scanner scanner = new Scanner(System.in); | ||
| public static String readString(String message) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Эта функция имеет модификатор public, а другие две функции ниже - нет, хотя логично было бы предположить, что эти три функции должны иметь один и тот же модификатор доступа (public)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
по-умолчанию проде они public и так идут, да ?
есть ли смысл явно прописывать ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
По умолчанию в джаве они package-private, то есть видимость на уровне пакета
В Котлине по умолчанию публичные, но есть случаи (например когда пишешь библиотеку) когда нужно прописывать явно
src/main/java/TerminalReader.java
Outdated
| } catch (NumberFormatException e) { | ||
| System.out.printf("\"%s\" не является числом%n", stringValue); | ||
|
|
||
| return readInt(message); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Рекурсия обычно не совсем подходит для решения задач из-за затрат по памяти и скорости работы (она проигрывает циклам), поэтому здесь лучше воспользоваться плоским циклом while (true), чтобы избежать использования рекурсии
|
@ArturNurtdinov все поправил, и добавил валидацию цены на отрицательное значение |
No description provided.